<template>
    <div class="bg">
      
        <div class="container">
            
            <!-- <div style="height: 360px; position: relative">
                <n-layout position="absolute">
                <n-layout-header style="height: 64px; padding: 24px" bordered>
                    颐和园路
                </n-layout-header>
                <n-layout has-sider position="absolute" style="top: 64px; bottom: 64px">
                    <n-layout-sider bordered content-style="padding: 24px;">
                    海淀桥
                    </n-layout-sider>
                    <n-layout content-style="padding: 24px;">
                    <n-h2>平山道</n-h2>
                    <n-h2>平山道</n-h2>
                    <n-h2>平山道</n-h2>
                    <n-h2>平山道</n-h2>
                    <n-h2>平山道</n-h2>
                    <n-h2>平山道</n-h2>
                    <n-h2>平山道</n-h2>
                    <n-h2>平山道</n-h2>
                    </n-layout>
                </n-layout>
                <n-layout-footer
                    bordered
                    position="absolute"
                    style="height: 64px; padding: 24px"
                >
                    城府路
                </n-layout-footer>
                </n-layout>
            </div> -->

 
            <div class="nav">
                <div @click="toHomePage">首页</div>
                <div>
                    <!--                选中的分类    选项            -->
                    <n-popselect @update:value="searchByCategory" v-model:value = "selectCategory" :options = "categortyOptions" trigger = "click">
                        <div>分类 <span>{{ categoryName }}</span> </div>
                        <!-- <div>{{ categoryName }}</div> -->
                    </n-popselect>
                </div>
                <div @click="toDashboard">后台</div>

                <div class="music"> 
                    <n-button @click="playMusic">
                        播放音乐
                    </n-button>
                 
                </div>
            </div>
            <n-divider/>
            

            <!-- 饼状图  -->
            <div class="data-chart">
                <v-chart class="chart" :option="option" />
            </div>
            <n-divider/>

            <n-space class="search">
                <n-input v-model:value="pageInfo.keyword" :style="{width: '500px'}"  placeholder="请输入关键字" />
                <n-button type="primary" ghost @click="loadBlogs(0)"> 搜索 </n-button>
            </n-space>

            <div class="rightcontent">
                <!-- 添加文章列表 -->
                <!-- cursor: pointer 手指悬浮效果 -->
                <div v-for="(blog,index) in blogListInfo" style="margin-bottom: 15px; cursor: pointer;">
                    <n-card :title ="blog.title" @click="toDetail(blog)">
                        {{ blog.content }}
                        <template #footer>
                                <n-space align = "center">
                                    <div>发布时间:{{ blog.create_time }}</div>
                                </n-space>
                        </template>
                    </n-card>
                </div>
            </div>

            <n-pagination @update:page="loadBlogs" v-model:page="pageInfo.page" :page-count="pageInfo.pageCount" />



            <!-- 加横线ui -->
            <n-divider/>
            <div class="footer">
                <div>Power by XXXX</div>
                <div>XICP备XXXXX号-1</div>
            </div>
        </div>
        



    </div>
</template>

<script setup>

    import { ref,reactive,inject ,onMounted,provide, computed, onBeforeMount,onBeforeUnmount,onUnmounted } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    // 数据柱状图
    import { use } from "echarts/core";
    import { CanvasRenderer } from "echarts/renderers";
    import { PieChart } from "echarts/charts";
    import {
    TitleComponent,
    TooltipComponent,
    LegendComponent
    } from "echarts/components";
    import VChart,{ THEME_KEY } from "vue-echarts"

    const router =  useRouter()
    const route = useRoute()

    const message = inject("message")
    const dialog = inject("dialog")
    const axios = inject("axios")

    const selectCategory = ref(0)
    const categortyOptions = ref([])
    const blogListInfo = ref([])
    let isPlaying = ref(true)
    const bgm = new Audio()


    const pageInfo = reactive({
        // 每页展示3条数据
        page:1,
        pageSize:3,
        // 初始化，默认页面最大数
        pageCount:0,
        // 数据最大值
        count:0,
        // 查询关键字
        keyword:"",
        // 查询功能内添加 分类id 参数
        categoryId:0
    })

    onBeforeMount(()=>{

       console.log('onBeforeMount start')
       bgm.src = '/Musics/bgm_op.mp3'
       bgm.loop = true
       bgm.volume = 0.5
    })
   

    // 页面完成加载后调用方法
    onMounted(()=>{
        bgm.play()

        loadCategorys();
        loadBlogs();
        
    })

    onBeforeUnmount(()=>{
        console.log("onBeforeUnmount")

    })

    onUnmounted(()=>{
        console.log("onUnmounted")

        if(isPlaying == true){
            bgm.pause()
            bgm.src = ''
        }
    })
    

    // 调取博客后台数据
    const loadBlogs = async ( page = 0 ) => {

        if(page != 0){
            pageInfo.page = page;
        }
 
        // let blogres = await axios.get("/blog/search")
        // 这里修改代码，用模板的方式传值,使用get方法,将页面和页面最大数据传到接口里,get接口增加关键字传参
        let blogres = await axios.get(`/blog/search?keyword=${pageInfo.keyword}&page=${pageInfo.page}&pageSize=${pageInfo.pageSize}&categoryId=${pageInfo.categoryId}`)
        let temp_rows = blogres.data.data.rows
        
        for(let row of temp_rows){
            row.content += "..."
            // 转换时间戳数据
            let d = new Date(row.create_time)
            row.create_time = `${d.getFullYear()}年${d.getMonth()+1}月${d.getDate()}日${d.getHours()}时${d.getMinutes()}分${d.getSeconds()}秒`
        }

        blogListInfo.value = temp_rows
        pageInfo.count = blogres.data.data.count;
        // 获取页面总数
        pageInfo.pageCount = parseInt(pageInfo.count / pageInfo.pageSize) + (pageInfo.count % pageInfo.pageSize > 0 ? 1 : 0);
        // console.log(blogres);
         
    }



    const categoryName = computed(()=>{
                                                    // 通过find 方法返回符合花括号条件内的值
        let selectOption = categortyOptions.value.find((option) => {return option.value == selectCategory.value})
        // 判断是否为空, 如果不为空范围 label 的值，否则返回 ""
        return selectOption? selectOption.label : ""
    })


    // 调用后端分类接口
    const loadCategorys = async () => {
        // 读取后端分类数据接口
        let res = await axios.get("/category/list")
        categortyOptions.value = res.data.rows.map((item)=>{
            return{
                label:item.name,
                value:item.id
            }
        })
        // console.log(categortyOptions.value)
     }



    use([
            CanvasRenderer,
            PieChart,
            TitleComponent,
            TooltipComponent,
            LegendComponent
        ]);

    provide(THEME_KEY, "light");

    // 饼状图样式
    const option = ref({
    title: {
        text: "饼状数据图",
        left: "center"
    },
    tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        orient: "vertical",
        left: "left",
        data: ["周一", "周二", "周三", "周四", "周五"]
    },
    series: [
        {
        name: "Traffic Sources",
        type: "pie",
        radius: "55%",
        center: ["50%", "60%"],
        data: [
            { value: 235, name: "周一" },
            { value: 210, name: "周二" },
            { value: 134, name: "周三" },
            { value: 155, name: "周四" },
            { value: 1548, name: "周五" }
        ],

        emphasis: {
            itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
            }
        }
        }
    ]
    });
     
    // 该方法有参数传递
    const searchByCategory = (categoryId) => {

        // console.log(event)
        // 通过获取分类id 参数，然后调用loadBlogs 方法查找数据库内的数据
        pageInfo.categoryId = categoryId
        loadBlogs()

    } 

    const toHomePage = () =>{
        router.push("/")
    }
    const toDashboard = () =>{
        router.push("/login")
    }

    const toDetail = (blog) =>{
         // 页面跳转传参写法  path路径，query ：传递参数
         router.push({path:"/detail",query:{id:blog.id}})

    }
 

    const playMusic = ()=>{
 
             
            isPlaying = isPlaying === true? false:true
 
            if(isPlaying){
                console.log("进入真")
                bgm.src = '/Musics/bgm_op.mp3'
                bgm.play()
                
            }
            else{
                console.log("进入假")
                bgm.pause()
                bgm.src = ''
            }
 
    }

</script>

<style lang="scss" scoped>

    .bg{
        // background-color: azure;
    }
    .data-chart{
        width: 1000px;
        height: 500px;
    }
    .chart{
        margin: 0 auto;
        width: 100%;
        height: 100%;
    }

    .container{
        width: 1200px;
        
        margin: 0 auto;
        // background-color: beige;
    }
    .nav{
        display: flex;
        font-size: 20px;
        padding-top: 20px;
        margin: 0 auto;
        // background-color: #f60;
        color: #64676a;
        div{
            cursor: pointer;
            margin-right: 15px;
            &:hover{
                color: #f60;
            }
            span{
                font-size: 12px;
            }
        }
    }

    .music{
        float: right;
        margin-left: auto;

    }

    .footer{
        margin: 0;
        padding: 0;
        text-align: center;
        line-height: 25px;
        color: #64676a;
        background-color: white;
    }
 
    .search{
        margin-bottom: 20px;
    }

</style>